<template>
  <div>
    <div class="search-container">
      <el-input
        v-model="monitorName"
        placeholder="名称"
        style="width: 10%; margin-right: 20px; margin-left: 20px; "
        class="rounded-input"
      />
      <el-input
        v-model="monitorAddress"
        placeholder="地址"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      />
      <el-select
        v-model="monitorCondition"
        placeholder="监测情况"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      >
        <el-option label="正常" value="0"></el-option>
        <el-option label="虫害较少" value="1"></el-option>
        <el-option label="虫害严重" value="2"></el-option>
        <el-option label="暂无" value="3"></el-option>
      </el-select>
      <el-select
        v-model="monitorType"
        placeholder="监测方式"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
      >
        <el-option label="人工监测" value="0"></el-option>
        <el-option label="无人机监测" value="1"></el-option>
      </el-select>
      <el-select
        v-model="createdBy"
        placeholder="创建人"
        style="width: 10%; margin-right: 20px;"
        class="rounded-input"
        filterable
      >
        <el-option
          v-for="creator in creators"
          :key="creator.id"
          :label="creator.name"
          :value="creator.id"
        />
      </el-select>
      <el-button
        type="text"
        icon="el-icon-search"
        @click="fetchData"
        style="margin-left: 0;"
      ></el-button>
      <el-button
        type="text"
        icon="el-icon-refresh"
        @click="resetSearch"
        style="margin-left: 10px;"
      ></el-button>
      <el-button
        type="text"
        icon="el-icon-question"
        @click="handleAI"
        style="margin-left: 150px;"
      >AI问答</el-button>
      <!-- 添加添加监测点按钮 -->
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="handleAddMonitorPoint"
        style="margin-left: 40px;"
      >
        添加监测点
      </el-button>
      </div>
    <el-table :data="paginatedData" style="width: 100%">
      <el-table-column prop="rowId" label="ID" width="100"></el-table-column>
      <el-table-column prop="monitorImage" label="记录" width="135">
        <template slot-scope="scope">
          <div class="image-container">
            <img :src="scope.row.monitorImage" alt="记录" class="record-image" />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="monitorName" label="名称" width="135"></el-table-column>
      <el-table-column prop="monitorAddress" label="地址" width="135"></el-table-column>
      <el-table-column prop="monitorCondition" label="监测情况" width="120"></el-table-column>
      <el-table-column prop="monitorType" label="监测方式" width="135"></el-table-column>
      <el-table-column prop="pest" label="病虫害" width="135"></el-table-column>
      <el-table-column prop="monitorIntroduce" label="症状" width="135"></el-table-column>
      <el-table-column prop="protective" label="防治措施" width="135"></el-table-column>
      <el-table-column prop="createdBy" label="创建人" width="135"></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleUpdate(scope.$index, scope.row)">数据上传</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3, 6, 9, 12]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
     <!-- 数据上传弹框 -->
     <el-dialog
      title="数据上传"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form :model="monitorData" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="记录图片">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :http-request="recordUpload"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="monitorData.monitorImage" :src="monitorData.monitorImage" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称">
              <el-input v-model="monitorData.monitorName" disabled></el-input>
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="monitorData.monitorAddress" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="监测情况">
              <el-radio-group v-model="monitorData.monitorCondition">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">虫害较少</el-radio>
                <el-radio label="2">虫害严重</el-radio>
                <el-radio label="3" disabled>暂无</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="监测方式">
              <el-select
                v-model="monitorData.monitorType"
                placeholder="监测方式"
                style="width: 100%; margin-right: 20px;"
                class="rounded-input"
              >
                <el-option label="人工监测" value="0"></el-option>
                <el-option label="无人机监测" value="1" disabled></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否自动识别" style="margin-left: 30px;">
              <el-radio-group v-model="monitorData.autoIdentify" @change="handleAutoIdentifyChange">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="病虫害">
              <el-select 
              v-model="monitorData.pest" 
              placeholder="请选择病虫害" 
              @change="fetchProtectiveByPest"
              multiple
              :disabled="isPestDisabled">
                <el-option
                  v-for="pest in pestOptions"
                  :key="pest.id"
                  :label="pest.pestName"
                  :value="pest.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="防治措施">
              <el-select v-model="monitorData.protective" placeholder="请选择防治措施" multiple disabled>
                <el-option
                  v-for="pro in protectiveOptions"
                  :key="pro.id"
                  :label="pro.protectiveName"
                  :value="pro.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="症状">
              <el-input
                type="textarea"
                :rows="4"
                v-model="monitorData.monitorIntroduce"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加监测点弹框 -->
    <el-dialog
      title="添加监测点"
      :visible.sync="addMonitorDialogVisible"
      width="60%"
      :before-close="handleAddMonitorClose"
    >
      <el-form :model="newMonitor" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="封面">
              <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                :http-request="newMonitorUpload"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="newMonitor.monitorPic" :src="newMonitor.monitorPic" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="名称">
              <el-input v-model="newMonitor.monitorName"></el-input>
            </el-form-item>
            <el-form-item label="地址">
              <el-input v-model="newMonitor.monitorAddress"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="坐标">
              <div id="mapContainer" style="width: 70%; height: 300px;"></div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="20">
            <el-form-item label="介绍">
              <el-input
                type="textarea"
                :rows="5"
                v-model="newMonitor.monitorIntroduce"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleAddMonitorClose">取 消</el-button>
        <el-button type="primary" @click="handleAddMonitorSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { selectPage, getCreators, getPest, getProtective, getById, update, getProtectiveByPest, add, upload } from '@/api/monitor';
export default {
  name: 'Monitor',
  data() {
    return {
      tableData: [], // 假设这是从API获取的数据
      currentPage: 1,
      pageSize: 6,
      total: 0,
      monitorName: '',
      monitorAddress: '',
      monitorType: null,
      monitorCondition: null,
      createdBy: null,
      creators: [],
      dialogVisible: false,
      monitorData: {
        id: null,
        monitorImage: '',
        monitorName: '',
        monitorAddress: '',
        monitorCondition: '',
        monitorType: '',
        autoIdentify: '0', // 默认选中否
        pest: [],
        protective: [],
        monitorIntroduce: ''
      },
      isPestDisabled: false, // 新增字段
      pestOptions: [],
      protectiveOptions: [],
      addMonitorDialogVisible: false,
      newMonitor: {
        monitorPic: '',
        monitorName: '',
        monitorAddress: '',
        monitorLat: null,
        monitorLon: null,
        monitorIntroduce: ''
      }
    };
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.tableData.slice(start, end).map((row,index) => ({
        ...row,
        rowId: start + index + 1
      }))
    },
  },
  created() {
    this.fetchData();
    // 获取病虫害选项
    this.fetchPestOptions();
    // 获取防治措施选项
    this.fetchProtectiveOptions();
  },
  mounted(){
    this.initMap();
  },
  methods: {
    initMap() {
      const map = new AMap.Map('mapContainer', {
        zoom: 10,
        center: [120.154354, 30.269398]
      });
      map.on('click', (e) => {
        this.addMarker(e.lnglat, map);
      }); 
    },

    addMarker(lnglat, map) {
      const marker = new AMap.Marker({
        position: lnglat,
        map: map,
        icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
        title: '标记点'
      });

      // 更新 newMonitor 对象
      this.newMonitor.monitorLat = lnglat.getLat();
      this.newMonitor.monitorLon = lnglat.getLng();

      // 清除之前的标记（可选）
      if (this.marker) {
        this.marker.setMap(null);
      }

      // 保存新的标记
      this.marker = marker;
      // 添加点击事件监听器
      marker.on('click', () => {
        marker.setMap(null); // 移除标记点
        this.newMonitor.monitorLat = null;
        this.newMonitor.monitorLon = null;
        this.marker = null; // 清除标记对象
      });
    },
    handleAutoIdentifyChange(value) {
      this.isPestDisabled = value === '1'; // 当选择“是”时禁用病虫害选项
    },
    fetchData() {
      const params ={
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        monitorName: this.monitorName,
        monitorAddress: this.monitorAddress,
        monitorType: this.monitorType,
        monitorCondition: this.monitorCondition,
        createdBy: this.createdBy
      };

      // 这是一个获取数据的API调用
      selectPage(params)
        .then(response => {
          this.tableData = response.data.result;
          this.total = response.data.total;
        })
        .catch(error => {
          console.error('获取数据失败', error);
        });

        getCreators()
        .then(response => {
          this.creators = response.data;
        })
        .catch(error => {
          console.error('获取数据失败', error);
        });
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },

    handleUpdate(index, row) {
      getById(row.id)
        .then(response => {
          const data = response.data;
          this.monitorData = {
            id: data.id,
            monitorImage: data.monitorImage,
            monitorName: data.monitorName,
            monitorAddress: data.monitorAddress,
            monitorCondition: data.monitorCondition,
            monitorType: data.monitorType,
            autoIdentify: '0', // 默认选中否
            pest: data.pests, // 假设 pest 是逗号分隔的字符串
            protective: data.protectives, // 假设 protective 是逗号分隔的字符串
            monitorIntroduce: data.monitorIntroduce
          };
          // 显示弹框
          this.dialogVisible = true;
        })
        .catch(error => {
          console.error('获取数据失败', error);
        });   
    },

    fetchProtectiveByPest() {
      if (this.monitorData.pest.length === 0) {
        this.monitorData.protective = [];
        return;
      }
      // 假设有一个 API 根据病虫害获取防治措施
      const pestIds = this.monitorData.pest.join(",");
      getProtectiveByPest(pestIds)
        .then(response => {
          // 如果需要自动选择防治措施，可以在这里处理
          this.monitorData.protective = response.data;
        })
        .catch(error => {
          console.error('获取防治措施失败', error);
        });
    },
    fetchPestOptions() {
      // 假设有一个 API 获取病虫害选项
      getPest()
        .then(response => {
          this.pestOptions = response.data;
        })
        .catch(error => {
          console.error('获取病虫害选项失败', error);
        });
    },

    fetchProtectiveOptions() {
      // 假设有一个 API 获取防治措施选项
      getProtective()
        .then(response => {
          this.protectiveOptions = response.data;
        })
        .catch(error => {
          console.error('获取防治措施选项失败', error);
        });
    },

    handleClose() {
      this.dialogVisible = false;
      this.monitorData = {
        id: null,
        monitorImage: '',
        monitorName: '',
        monitorAddress: '',
        monitorCondition: '',
        monitorType: '',
        autoIdentify: '0', // 默认选中否
        pest: [],
        protective: [],
        monitorIntroduce: ''
      }
    },

    handleSubmit() {
      // 处理提交逻辑
      console.log('提交数据', this.monitorData);
      const param = {
        id: this.monitorData.id,
        monitorImage: this.monitorData.monitorImage,
        monitorCondition: this.monitorData.monitorCondition,
        autoIdentify: this.monitorData.autoIdentify,
        pest: this.monitorData.pest,
        monitorIntroduce: this.monitorData.monitorIntroduce
      }
      // 你可以在这里调用API提交数据
      update(param).then(response => {
        console.log('更新成功', response);
        if(response.code == 200){
          // this.$message({
          //   message: '更新成功！',
          //   type: 'success'
          // });
        }else{
          this.$message({
            message: response.data,
            type: 'error'
          });
        }
        this.dialogVisibleUpdate = false; // 关闭对话框
        this.handleClose();
        this.fetchData(); // 重新获取数据
      }).catch(error => {
        console.error('更新失败', error);
      });
    },

    resetSearch() {
      // 清空搜索框中的所有输入并恢复默认选项
      this.monitorName = null,
      this.monitorAddress = null;
      this.monitorCondition = null,
      this.monitorType = null,
      this.createdBy = null,
      this.fetchData(); // 重新获取数据
    },

    handleAI() {
      this.$router.push({ name: 'AI' });
    },

    beforeAvatarUpload(file) {
      const isValidType = ['image/jpeg', 'image/png'].includes(file.type);
      const isValidSize = file.size / 1024 / 1024 < 2;

      if (!isValidType) {
        this.$message.error('只能上传 JPG/PNG 格式的图片');
        return false;
      }

      if (!isValidSize) {
        this.$message.error('图片大小不能超过 2MB');
        return false;
      }

      return true;
    },

    recordUpload(options) {
      const { file } = options;
      const bucket = 'pest-control';             // 固定 bucket
      const objectName = 'image';                // 固定目录名

      upload(file, bucket, objectName)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.monitorData.monitorImage = response.data; // 接收返回的 URL
            this.$message.success('上传成功');
          } else {
            this.$message.error('上传失败：' + (response.message || '未知错误'));
          }
        })
        .catch(() => {
          this.$message.error('请求出错，请重试');
        });
    },

    newMonitorUpload(options) {
      const { file } = options;
      const bucket = 'pest-control';             // 固定 bucket
      const objectName = 'image';                // 固定目录名

      upload(file, bucket, objectName)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.newMonitor.monitorPic = response.data; // 接收返回的 URL
            this.$message.success('上传成功');
          } else {
            this.$message.error('上传失败：' + (response.message || '未知错误'));
          }
        })
        .catch(() => {
          this.$message.error('请求出错，请重试');
        });
    },

    handleAddMonitorPoint() {
      this.addMonitorDialogVisible = true;
      this.$nextTick(() => {
        this.initMap();
      })
    },
    handleAddMonitorClose() {
      this.addMonitorDialogVisible = false;
      this.newMonitor = {
        monitorImage: '',
        monitorName: '',
        monitorAddress: '',
        latitude: '',
        longitude: '',
        monitorIntroduce: ''
      };
    },
    handleAddMonitorSubmit() {
      // 处理提交逻辑
      console.log('提交数据', this.newMonitor);
      // 你可以在这里调用API提交数据
      if (this.newMonitor.monitorLat == null 
      || this.newMonitor.monitorLon == null) {
        this.$message({
          message: '坐标不能为空',
          type: 'warning'
        });
        return;
      }
      // 提交表单逻辑
      console.log('添加病虫害', this.addForm);
      // 你可以在这里调用API提交数据
      add(this.newMonitor)
        .then(response => {
          console.log('添加成功', response);
          this.addMonitorDialogVisible = false;
          if(response.code === 200){
            this.$message({
              message: "添加成功!",
              type: 'success'
            });
            this.dialogVisibleAdd = false;
            this.resetForm();
            this.fetchData(); // 重新获取数据
          }else{
            this.$message({
              message: response.message,
              type: 'error'
            });
          }
        })
        .catch(error => {
          console.error('新增失败', error);
        });
    }
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}

.avatar {
  width: 150px;
  height: 150px;
  display: block;
  border: 2px solid #d9d9d9; /* 添加外边框 */
  border-radius: 6px; /* 可选：添加圆角 */
}

.search-container {
  margin-bottom: 20px;
  margin-top: 20px;
  display: flex;
  align-items: center;
}

.rounded-input .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}


.rounded-input:last-child .el-input__inner {
  border-radius: 20px;
  margin-right: 10px;
}

.el-select .el-input__inner {
  border-radius: 20px;
  width: 15%;
  margin-right: 10px;
}

.el-button--text {
  padding: 0; /* 去掉按钮的内边距 */
  margin-left: 10px; /* 调整按钮的左边距 */
  font-size: 20px;
}

.monitor-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh; /* 确保容器至少占满整个视口高度 */
  padding: 20px;
  box-sizing: border-box;
}

.monitor-table {
  width: 100%;
  flex: 1; /* 使表格内容占据剩余空间 */
  margin-bottom: 20px;
}

.record-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
}

.pagination-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-top: 20px;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff; /* 确保背景颜色与页面一致 */
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  padding: 10px;
  box-sizing: border-box;
}

.el-table {
  margin-bottom: 60px; /* 根据分页组件的高度调整这个值 */
}

/* 弹框样式 */
.dialog-content {
  display: flex;
  flex-direction: column;
}

.row {
  display: flex;
  margin-bottom: 20px;
}

.row .left {
  flex: 1;
  margin-right: 20px;
}

.row .right {
  flex: 1;
}

.record-image {
  width: 100%;
  height: auto;
  max-height: 150px;
  object-fit: cover;
}

.name-address {
  display: flex;
  flex-direction: column;
}

.name-address .name,
.name-address .address {
  margin-bottom: 10px;
}

.condition,
.monitor-type,
.auto-identify,
.pest,
.symptom {
  display: flex;
  align-items: center;
}

.condition .el-radio-group,
.monitor-type .el-input,
.auto-identify .el-radio-group,
.pest .el-checkbox-group,
.symptom .el-input {
  margin-left: 10px;
}

.symptom .el-input {
  width: 100%;
}
</style>


